<template>
	<el-row id="container">

		<Header></Header>

		<el-col :span="24" id="outter_container">
			<el-col :span="14" :offset="5" id="content_container">

				<el-col :span="24" id="blocktitle">
					<div id="title"> <span>区块详细</span> </div>

					<el-breadcrumb separator="/" id="breadcrumb">
						<el-breadcrumb-item class="breadcrumblink" :to="{ path: '/' }">主页</el-breadcrumb-item>
						<el-breadcrumb-item class="breadcrumblink" :to="{ path: '/blocks' }">区块</el-breadcrumb-item>
						<el-breadcrumb-item id="currentpage">区块详细</el-breadcrumb-item>
					</el-breadcrumb>
				</el-col>

				<el-col :span="24" id="blocksinfo">
					<el-table :data="tableData" style="width: 100%" @row-click="route2other" 
					:cell-style="cellStyle">
						<el-table-column prop="mkey" align="left" width="130%" label="区块信息"></el-table-column>
						<el-table-column prop="mvalue" align="left"></el-table-column>
					</el-table>
				</el-col>

				<el-col :span="24" id="blockstx" v-bind:class="txNum()">
					<el-col :span="24" id="transactionsitle">
						<div id="title"> <span>本区块交易</span> </div>
					</el-col>

					<el-col :span="24" id="txsinfo">
						<el-table :data="txtableData" height="100%" style="width: 100%" :row-style="rowClass" @row-click="readdetail" id="txsinfotable">
							<el-table-column prop="type" width="125%" label="类型" align="left"/>
							<el-table-column prop="extra.marketName" width="160%" label="所属市场" align="left"/>
							<el-table-column width="20%"/>
							<el-table-column prop="txHash" width="400%" label="交易ID" align="left"/>
							
							<el-table-column prop="mark" label="单号" width="180%" align="left"/>
							<el-table-column prop="time" label="时间" width="180%" align="left" :formatter="timeformatter"/>
						</el-table>
					</el-col>

					<el-col :span="24" id="paging">
						<el-pagination id="pagingc" :page-size="5" background @current-change="handleCurrentChange" layout="prev, pager, next" :total="total"></el-pagination>
					</el-col>
				</el-col>
			</el-col>
		</el-col>

		<Footer></Footer>

	</el-row>
</template>

<script>

	import Header from '../components/header1.vue'
	import Footer from '../components/footer.vue'

	export default {

		components: { 
			Header, 
			Footer 
		},

		data () {
			return {
				// list: [],
				cblockdetail: "",
				cloadbus: false,
				tableData: [],
				txtableData: [],
				txde:[],
				cmount: false,
				txsflag: 1,
				total: 0,
				fflag: 1,
				currentPage: 1,
				txlist: []
			}
		},

		created () {
			eventBus.$on('blockdetail',blockdetail => {
				// console.log(blockdetail)
				//异步接收数据，若第一次加载该页面则blockdetail应不为空
				if (blockdetail != "" && blockdetail != undefined) {
					// console.log(blockdetail)
					// console.log("<<<<<<")
					this.cloadbus = true
					window.localStorage.setItem(this.$route.params.id,JSON.stringify(blockdetail))
					this.setData(blockdetail.data)
					this.settxData(blockdetail.data)
					this.cblockdetail = blockdetail
				} else if (blockdetail === undefined) {
					// let param = {hash:JSON.parse(this.$route.params.id)} 
					// console.log(this.$route.params.id)
					// this.$api.post('blockchain/block', param, r => {
					// 	// this.$router.push(`/blocks/${JSON.stringify(r.data.hash)}`)
					// 	console.log("asfasfs")
					// 	this.tableData = []
					// 	this.txtableData = []
					// 	this.txde = []
					// 	this.cloadbus = true
					// 	window.localStorage.setItem(this.$route.params.id,JSON.stringify(r))
					// 	this.setData(r.data)
					// 	this.settxData(r.data)
					// 	this.cblockdetail = r
					// })
				}
			})

		},

		mounted () {
			if (this.cloadbus === false) {
				this.cmount = true
				let s = this.$route.params.id
				this.cblockdetail = JSON.parse(window.localStorage[s])
				this.setData(this.cblockdetail.data)
				this.settxData(this.cblockdetail.data)
			}
			eventBus.$off('blockdetail')
		},

		beforeRouteUpdate(to,from,next){
			// if (this.cmount === false) {
			this.tableData = []
			this.cblockdetail = JSON.parse(window.localStorage.getItem(to.params.id))
			this.setData(this.cblockdetail.data)
			this.fflag = 1
			this.total = 0
			this.settxData(this.cblockdetail.data)
			// }
			// this.cmount = false
			next()
		},

		destroyed () {
			eventBus.$emit('txdetail',this.txlist)
		},

		methods: {

			txNum: function () {
				return {
					'txnum0': this.txsflag === 0,
					'txnumnot0': this.txsflag != 0
				}
			},

			cellStyle({row, column, rowIndex, columnIndex}){
				 if(rowIndex === 3 && columnIndex === 1){ //指定坐标
			        return {
			        	"color":"#1DB2BF",
			        	"cursor": "pointer"
			        }
			    }
			},

			headerStyle({row, rowIndex}) {
            	return {
            		"background": "#F2F2F4",
            		"color": "#333333"
            	}
            },

			route2other (row, event, column) {
				// console.log(row.mkey[0])
				if(row.mkey[0].toString()==="前一区块：")
				{
					let param = {hash:row.mvalue[0].toString()}
					this.$api.post('blockchain/block', param, r => {
						// this.tableData = []
						// this.cblockdetail = r
						window.localStorage.setItem(JSON.stringify(r.data.hash),JSON.stringify(r))
						// this.setData(this.cblockdetail.data)
						// this.fflag = 1
						// this.total = 0
						// this.settxData(this.cblockdetail.data)
						this.$router.push(`/blocks/${JSON.stringify(r.data.hash)}`)
					})
				}
			},

			setData (blockdetail){

				let temparray = []
				let temphash = {mkey:[],mvalue:[]}

				for( let p in blockdetail) {
					temphash = {mkey:[],mvalue:[]}

					if (p==="mineTime")
					{
						let date
						if(blockdetail[p].toString().length===10)
						{
							date = new Date(blockdetail[p] * 1000)
						} else {
							date = new Date(blockdetail[p])
						}
						let a = [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-')
						function paddNum(s) {
							s += ""
							return s.replace(/^(\d)$/,"0$1");
						}
						let h = paddNum(date.getHours());
						let m = paddNum(date.getMinutes());
						let s = paddNum(date.getSeconds());
						a = a + " " + h + ":" + m + ":" + s
						if (date.getHours() < 12) {
							a = a + " AM"
						} else {
							a = a + " PM"
						}
						temphash["mvalue"].push(a)
					} else if (p==="size") {
						let a = blockdetail[p] + " Bytes"
						temphash["mvalue"].push(a)
					} else {
						temphash["mvalue"].push(blockdetail[p])
					}

					if (p==="txs") {
						if(blockdetail[p] === 0) {
							this.txsflag = 0
						} else {
							this.txsflag = 1
						}
					}

					switch(p)
					{
						case "number": p="序号："; break;
						case "mineTime": p="时间："; break;
						case "hash": p="区块ID："; break;
						case "preHash": p="前一区块："; break;
						case "size": p="大小："; break;
						case "txs": p="交易数："; break;
					}

					temphash["mkey"].push(p)
					this.tableData.push(temphash)
				}
			},

			settxData (d) {
				if (d.number != 0) {
					let param = {number:d.number}
					this.txtableData = []
					if (this.fflag === 1){
						// sleep(1000)
						this.$api.post('blockchain/txsOfBlock', param, r => {
							this.txde = r.data
							this.fflag = 0
							if (this.total === 0) {
								this.total = r.data.length
							}
							this.txde.forEach(function(i,index) {
								let a
								switch (i.type) {
									case "RetailInfo": a="零售单"; i["type"]=a; break;
									case "SaleInfo" : a="销售单"; i["type"]=a; break;
									case "PurchaseInfo" : a="进货单"; i["type"]=a; break;
									case "ReceiveInfo" : a="收货单"; i["type"]=a; break;
									case "AccessCertificate" : a="准入证明"; i["type"]=a; break;
									case "Market" : a="市场检查表"; i["type"]=a; break;
									case "Gov" : a="日常检查表"; i["type"]=a; break;
									default : console.log("haven't such type"); break;
								}
							})
							
							let s = (this.currentPage - 1) * 5 + 1
							// console.log(this.currentPage)
							let q = 0
							if ((s+4)>this.total) {
								q = this.total
							} else {
								q = s + 4
							}
							
							for(let i = 1;i <= q; i++){
								// console.log("asasfas")
								this.txtableData.push(this.txde[i - 1])
							}
							// console.log(this.txtableData)
						})
					} else {
						
						let s = (this.currentPage - 1) * 5 + 1
						let q = 0
						if ((s+4)>this.total) {
							q = this.total
						} else {
							q = s + 4
						}
						for(let i = s;i <= q; i++){
							this.txtableData.push(this.txde[i - 1])
						}
					}
				}
			},

			readdetail(row, event, column) {
				let param = {
					txHash:row.txHash
				}

				this.$api.post('blockchain/tx', param, r => {
					this.txlist = r
					this.$router.push(`/transactions/${JSON.stringify(r.data.txHash)}`)
				})

			},

			rowClass: function (row, index) {
				return { 
					"cursor": "pointer"
					// "font-size": "0.77vw"
				}
			},

			timeformatter: function(row, column) {
				let date

				if(row.time.toString().length===10)
				{
					date = new Date(row.time * 1000)
				} else {
					date = new Date(row.time)
				}

				let a = [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-')
				function paddNum(s) {
					s += ""
					return s.replace(/^(\d)$/,"0$1");
				}
				let h = paddNum(date.getHours());
				let m = paddNum(date.getMinutes());
				let s = paddNum(date.getSeconds());
				a = a + " " + h + ":" + m + ":" + s
				// if (date.getHours() < 12) {
				// 	a = a + " AM"
				// } else {
				// 	a = a + " PM"
				// }
				return a
			},

			handleCurrentChange(val){
              this.currentPage = val
              this.settxData(this.cblockdetail.data)
            }

		}
	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

	
	#currentpage>>>.el-breadcrumb__inner{
		font-size: 0.9vw;
		color: #1DB2BF;
	}

	.breadcrumblink>>>.el-breadcrumb__inner{
		font-size: 0.9vw;
		font-weight: 400;
	}

	.breadcrumblink>>>.el-breadcrumb__inner.is-link:hover {
		color: #1DB2BF;
	}

	#breadcrumb {
		float: right;
		/*font-size: 0.83vw;*/
		position: relative;
        top: 50%; 
        margin-top: -1.1vw;
	}

	#container {
		position: absolute;
		margin-top: 0px;
		margin-bottom: 0px;
		height: 100%;
		width: 100%;
		overflow: hidden;
		box-sizing: border-box;
	}

	#outter_container {
		height: 82.6%;
		margin-top: 4.5px;
	}

	#content_container {
		/*min-height: 579.4px;*/
		height: 100%;
		background-color: rgb(248, 248, 248);
		padding: 18px;
		padding-top: 10px;
		overflow-y: auto;
	}

	#blocktitle {
		height: 8.1%;
		border-bottom:2px solid #E6E6E6;
	}

	#blocksinfo {
		margin-top: 2%;
		overflow-y: auto;
	}

	#title {
		font-size: 1.2vw;
		position: relative;
        top: 50%; 
        margin-top: -1vw;
	}




	#blockstx {
		margin-top: 2%;
		height: 70%;
	}

	.txnum0 {
		display: none;
	}

	.txnumnot0 {
		display: block;
	}

	#transactionsitle {
		height: 8.1%;
		border-bottom:2px solid #E6E6E6;
	}

	#txsinfo{
		height: 78%;
		margin-bottom: 1%;
		margin-top: 2%;
	}

	#txsinfotable {
		/*text-align: center;*/
		/*cursor: pointer;*/
		text-align: center;
		/*min-height: 404px;*/
	}

	#paging {
		text-align:center;
		/*margin: 0 auto;*/
		height: 4.1%;
	}

	#pagingc {
		position: relative;
        top: 50%;
        margin-top: -14px;
	}

</style>